package com.example.wanbaqian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.authreal.api.AuthBuilder;
import com.authreal.api.OnResultListener;
import com.bqs.risk.df.android.BqsDF;
import com.bqs.risk.df.android.BqsParams;
import com.example.wanbaqian.R;
import com.example.wanbaqian.adapter.ApplyTwoAdapter;
import com.example.wanbaqian.base.BaseActivity;
import com.example.wanbaqian.bean.UserInfoBean;
import com.example.wanbaqian.config.CommonValue;
import com.example.wanbaqian.base.HttpCallback;
import com.example.wanbaqian.config.HttpURL;
import com.example.wanbaqian.bean.ApplyTwoBean;
import com.example.wanbaqian.bean.Info;
import com.example.wanbaqian.utils.DesUtils;
import com.example.wanbaqian.utils.GetJsonUtils;
import com.example.wanbaqian.utils.HttpUtils;
import com.example.wanbaqian.utils.JsonUtils;
import com.example.wanbaqian.utils.SPUtils;
import com.moxie.client.MainActivity;
import com.moxie.client.model.MxParam;
import com.umeng.socialize.UMShareAPI;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.tongdun.android.shell.FMAgent;

/**
 * 申请第二步
 */
public class ApplyTwoActivity extends BaseActivity implements ApplyTwoAdapter.ApplyTwoListeren, HttpCallback, OnResultListener {
    private static final String TAG = "ApplyTwoActivity";
    @BindView(R.id.ApplyTwo_RecyclerView)
    RecyclerView ApplyTwoRecyclerView;
    private ApplyTwoBean itemBean;
    private List<ApplyTwoBean> list = new ArrayList<>();
    private ApplyTwoAdapter adapter;
    private boolean stats;
    String[] userAndBankStat = new String[]{"未完善", "未完善"};
    private String[] stats1;
    private String bank_account;
    private String tokenkey;
    private String idCardNO;
    private String realName;

    @Override
    protected int getLayout() {
        return R.layout.activity_apply;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setStatusBarColor(R.color.main_color);
        setToolBar("额度申请");
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        getDate();
        initBqsDFSDK();
        adapter = new ApplyTwoAdapter(list, mContext, userAndBankStat);
        ApplyTwoRecyclerView.setAdapter(adapter);
        adapter.setItemClick(this);
        ApplyTwoRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
    }

    private void getDate() {
        itemBean = new ApplyTwoBean(R.drawable.emergency_people, "紧急联系人", "特殊情况,可以联系到你", "未完善");
        list.add(itemBean);

//        itemBean = new ApplyTwoBean(R.drawable.work, "工作信息", "请填写你的工作信息", "未完善");
//        list.add(itemBean);

        itemBean = new ApplyTwoBean(R.drawable.people_mobile, "手机运营商", "手机运营商有助加快审核", "未完善");
        list.add(itemBean);

        itemBean = new ApplyTwoBean(R.drawable.alipay_zm, "芝麻信用", "阿里体系的信用查询", "未完善");
        list.add(itemBean);
//        itemBean = new ApplyTwoBean(R.drawable.taobao_zx, "淘宝授权认证", "淘宝订单账号", "未完善");
//        list.add(itemBean);
//        itemBean = new ApplyTwoBean(R.drawable.tencen_zx, "QQ授权", "获取QQ基本信息", "未完善");
//        list.add(itemBean);
//        itemBean = new ApplyTwoBean(R.drawable.xl, "学历信息", "获取基本的学历信息", "未完善");
//        list.add(itemBean);
//        itemBean = new ApplyTwoBean(R.drawable.wx, "身份认证", "", "未完善");
//        list.add(itemBean);
//        itemBean = new ApplyTwoBean(R.drawable.wx, "银行卡认证", "", "未完善");
//        list.add(itemBean);
//        itemBean = new ApplyTwoBean(R.drawable.wy, "网上银行", "获取银行卡的基本信息", "未完善");
//        list.add(itemBean);
    }

    @Override
    protected void initDate() {
        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.AUTH_CERT, mContext,
                new String[]{"accessid"}, new String[]{SPUtils.getAccessid(mContext)}), HttpURL.AUTH_CERT, CommonValue.REQUEST_CODE2, this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUIMethod();
    }


    /**
     * 白骑士配置
     */
    private void initBqsDFSDK() {
        //1、配置初始化参数
        BqsParams params = new BqsParams();
        params.setPartnerId(CommonValue.PARTNERID);//商户编号
        params.setTestingEnv(false);//false是生产环境 true是测试环境
        params.setGatherGps(true);
        params.setGatherContact(true);
        params.setGatherCallRecord(true);
        //2、执行初始化
        BqsDF.initialize(this, params);
        //3、提交tokenkey到贵公司服务器
        tokenkey = BqsDF.getTokenKey();
    }

    /**
     * 点击事件，case 0：身份证以及人脸
     *          case 1：银行卡
     * @param position
     */
    @Override
    public void headClick(int position) {
        if(null == stats1){
            return;
        }
        switch (position) {

            case 0:
                if (stats1[3].startsWith("已完善")) {
                    showToast("您已实名认证完毕");
                } else {
                    try {
                        //有盾人脸识别
                        AuthBuilder mAuthBuidler = new AuthBuilder("1354321032456123", CommonValue.TDAUTHKEY, "", this);
                        mAuthBuidler.faceAuth(this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                break;
            case 1:
                if (stats1[3].startsWith("未完善")) {
                    showToast("先填写身份认证信息");
                } else if (stats1[4].startsWith("已完善")){
                    showToast("您银行卡已认证完毕");
                }else {
                    Bundle bundle = new Bundle();
                    bundle.putString("bank_account", bank_account);
                    openActivity(FindEdiBankActivity.class, bundle);
                }
                break;
            case -1:

                //2017-9-20 14:32:18注释内容：取消工作信息：执行人刘欢 苗佳
//                if (stats1[1].startsWith("未完善")) {
//                    showToast("请添加工作信息");
//                } else

               /* //TODO 需要获取同盾blackBox传给后台
                String blackBox = FMAgent.onEvent(ApplyTwoActivity.this);
                //先实时取，取不到，再取本地的
                if(TextUtils.isEmpty(blackBox)){
                    blackBox = ((String) SPUtils.get(this, "tdJava", ""));
                }
                Log.e("TD_JAVA", "setSubmin_blackBox: " + blackBox);

                UserInfoBean userInfo = SPUtils.getUserInfo(mContext);
                //用的登录手机号
                String phone = userInfo.getLogin_mobile();
                Log.e("TD_JAVA", "setSubmin: "+phone);
*/
                if (stats1[3].startsWith("未完善")) {
                    showToast("先填写身份认证信息");
                } else if (stats1[4].startsWith("未完善")) {
                    showToast("请添加银行卡信息");
                } else if (stats1[0].startsWith("未完善")) {
                    showToast("请添加紧急人");
                } else if (stats1[1].startsWith("未完善")) {
                    showToast("请审核手机运营商");
                } else if(stats1[2].startsWith("未完善")){
                    showToast("请审核芝麻信用");
                }else{
                    //注意：上传tokenkey时最好再停留几百毫秒的时间（给SDK预留上传设备信息的时间）
                    new CountDownTimer(500, 500) {
                        @Override
                        public void onTick(long l) {
                        }

                        @Override
                        public void onFinish() {
                            setSubmin();
                        }
                    }.start();
                }
                break;
        }
    }

    /**
     * 提交审核
     */
    private void setSubmin() {
        //同盾获取黑匣子String传给后台

        //TODO 需要获取同盾blackBox传给后台
        String blackBox = FMAgent.onEvent(ApplyTwoActivity.this);
        //先实时取，取不到，再取本地的
        if(TextUtils.isEmpty(blackBox)){
            blackBox = ((String) SPUtils.get(this, "tdJava", ""));
        }
        Log.e("TD_JAVA", "setSubmin_blackBox: " + blackBox);
        UserInfoBean userInfo = SPUtils.getUserInfo(mContext);
        //用的登录手机号
        String phone = userInfo.getLogin_mobile();
        Log.e(TAG, "setSubmin: "+phone);

        String bodyCpm = GetJsonUtils.getInstance().getRequest(HttpURL.AUTH_SUBMIT, mContext,
                new String[]
                        {
                                "accessid",
                                "cert_agree_flag",
                                "baiqishi_id",
                                "black_box",
                                "user_mobile"

                        },
                new String[]
                        {
                                SPUtils.getAccessid(mContext),
                                "1",
                                tokenkey,
                                ""+blackBox,
                                ""+phone
                        });
        Log.e("TD_JAVA", "setSubmin_入参: " + bodyCpm);

        HttpUtils.getInstance().post(""+bodyCpm,mContext, null, CommonValue.REQUEST_CODE4, this);
    }

    @Override
    public void itemClick(int position) {
        MxParam mxParam = new MxParam();
        mxParam.setUserId(SPUtils.getUserInfo(mContext).getUser_id() + "");

//        mxParam.setApiKey(CommonValue.TDAUTHKEY);
        //魔蝎APIKey2017年9月8日10:27:07修改为下面
        mxParam.setApiKey(CommonValue.MX_API_KEY);
        if(null == stats1){
            return;
        }

        mxParam.setBannerBgColor("#1BBFA1"); // SDK里Banner的背景色
        mxParam.setBannerTxtColor("#FFFFFF"); // SDK里Banner的字体颜色
        Bundle bundle = new Bundle();
        switch (position) {
            case 0:
                if (stats1.length > 0) {
                    if (stats1[3].startsWith("未完善")) {
                        showToast("先填写身份认证信息");
                    } else if (stats1[4].startsWith("未完善")) {
                        showToast("请添加银行卡信息");
                    } else if(stats1[0].startsWith("已完善")){
                        showToast("您已完善紧急联系人");
                    }else {
                        //紧急联系人
                        openActivity(EmergencyContactActivity.class);
                    }

                } else {
                    showToast("系统忙，请重试");
                }
                break;
            case 1:
                if (stats1.length > 0) {
                    if (stats1[3].startsWith("未完善")) {
                        showToast("先填写身份认证信息");
                    } else if (stats1[4].startsWith("未完善")) {
                        showToast("请添加银行卡信息");
                    } else if (stats1[0].startsWith("未完善")) {
                        showToast("请添加紧急人");
                    } else if(stats1[1].startsWith("已完善")){
                        showToast("您已验证手机运营商");
                    }else{
                        //手机运营商
                        mxParam.setFunction(MxParam.PARAM_FUNCTION_CARRIER);

                        //2017年10月9日 魔蝎手机运营商自动填写三要素

                        if(!TextUtils.isEmpty(idCardNO)){
                            UserInfoBean userInfo = SPUtils.getUserInfo(this);
                            String mobile = userInfo.getLogin_mobile();
                            HashMap<String, String> extendParam = new HashMap<>();
                            extendParam.put(MxParam.PARAM_CARRIER_IDCARD, ""+idCardNO); // 身份证
                            extendParam.put(MxParam.PARAM_CARRIER_PHONE, ""+ mobile); // 手机号
                            extendParam.put(MxParam.PARAM_CARRIER_NAME, ""+realName); // 姓名
                            mxParam.setExtendParams(extendParam);
                        }
                        bundle.putParcelable("param", mxParam);

                        openActivityForResult(MainActivity.class, bundle, CommonValue.REQUEST_CODE4);
                    }

                } else {
                    showToast("系统忙，请重试");
                }
                break;
//            case 2://工作信息
//                if (stats1.length > 0) {
//                    if (stats1[3].startsWith("未完善")) {
//                        showToast("先填写身份认证信息");
//                    } else if (stats1[4].startsWith("未完善")) {
//                        showToast("请添加银行卡信息");
//                    } else if (stats1[0].startsWith("未完善")) {
//                        showToast("请添加紧急人");
//                    } else/* if (stats1[1].startsWith("未完善")) {
//                        showToast("请添加工作信息");
//                    } else */{
//                        //手机运营商
//                        mxParam.setFunction(MxParam.PARAM_FUNCTION_CARRIER);
//                        bundle.putParcelable("param", mxParam);
//                        openActivityForResult(MainActivity.class, bundle, CommonValue.REQUEST_CODE4);
////                openActivity(MobileOperatorActivity.class);
//                    }
//                } else {
//                    showToast("系统忙，请重试");
//                }
//                break;

            case 2://芝麻原本3
                if (stats1.length > 0) {
                    if (stats1[3].startsWith("未完善")) {
                        showToast("先填写身份认证信息");
                    } else if (stats1[4].startsWith("未完善")) {
                        showToast("请添加银行卡信息");
                    } else if (stats1[0].startsWith("未完善")) {
                        showToast("请添加紧急人");
                    } else /*if (stats1[1].startsWith("未完善")) {
                        showToast("请添加工作信息");
                    } else */if (stats1[1].startsWith("未完善")){
                        showToast("请审核手机运营商");
                    }else if(stats1[2].startsWith("已完善")){
                        showToast("您已完善芝麻信用");
                    }else{
                        //芝麻信用

                        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.THIRD_ZHIMA, mContext,
                                new String[]{"accessid"},
                                new String[]{SPUtils.getAccessid(mContext)}),
                                mContext,
                                null,
                                CommonValue.REQUEST_CODE5,
                                this);
                    }
                } else {
                    showToast("系统忙，请重试");
                }
                break;
        }
    }

    /**
     * 回调
     * CommonValue.REQUEST_CODE4:手机运营商
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
//                case CommonValue.REQUEST_CODE1:
//                case CommonValue.REQUEST_CODE2:
//                case CommonValue.REQUEST_CODE3:
                case CommonValue.REQUEST_CODE4:
                    String result = data.getExtras().getString("result");
                    Log.i(TAG, "onActivityResult手机运营商获取到的身份信息数据: " + result);
                    if (JsonUtils.getInstance().getInt(result, "code") == 1) {
                        HttpUtils.getInstance().post(

                                GetJsonUtils.getInstance().getRequest(HttpURL.THIRD_RESPONSE, mContext,
                                new String[]
                                        {
                                                "accessid"
                                                , "response_type"
                                                , "response_info"
                                        },
                                new String[]
                                        {
                                                SPUtils.getAccessid(mContext)
//                                                ,requestCode == CommonValue.REQUEST_CODE1 ? CommonValue.study : requestCode == CommonValue.REQUEST_CODE2 ? CommonValue.QQ :
//                                                        requestCode == CommonValue.REQUEST_CODE3 ? CommonValue.taobao : CommonValue.mobile
                                                ,CommonValue.mobile
                                                , result}),
                                "", CommonValue.REQUEST_CODE7, this);
                    } else {
                        showToast("数据获取失败");
                    }
                    break;
            }
        }
    }

    @Override
    public void footClick(boolean stat) {
        stats = stat;
    }

    @Override
    public void onSuccess(String content, Info info, int requestCode) {
        switch (requestCode) {
            case CommonValue.REQUEST_CODE1:
//                list.get(list.size() - 3).setStat("已完善");
                showToast("微信授权成功");
//                adapter.notifyDataSetChanged();
                //2017年9月27日12:48:19  修改
                updateUIMethod();
                break;
            case CommonValue.REQUEST_CODE2:
//                adapter.setContent(content);
//                adapter.notifyDataSetChanged();
                break;
            case CommonValue.REQUEST_CODE3:
                /**
                 * 获取到各项认证信息以及状态
                 */
                Log.i(TAG, "所有状态返回: " + content);
                try {
                    JSONObject object = new JSONObject(content);
                    bank_account = object.getString("bank_account");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.e(TAG, "认证状态返回onSuccess: "+content);

                /**
                 * emergency_fill_flag  紧急联系人
                 * mobile_fill_flag     手机运营商
                 * job_fill_flag        工作信息
                 * zhima_fill_flag      芝麻信用
                 *
                 * realname_fill_flg    身份证以及人脸识别
                 * bank_fill_flg        银行卡信息
                 *
                 * zm_score         芝麻分  int类型
                 *
                 * stats1           用来存储紧急联系人、手机运营商以及芝麻信用状态
                 * userAndBankStat  用来存储身份证信息以及银行卡信息状态
                 */
                stats1 = JsonUtils.getInstance().getInfoStat(content,
                        "emergency_fill_flag", "mobile_fill_flag"
                        ,"zhima_fill_flag", "realname_fill_flg", "bank_fill_flg");

                for (int i = 0; i < stats1.length - 2; i++) {
                    list.get(i).setStat(stats1[i]);
                    Log.e(TAG, "onSuccess11: " + stats1[i]);
                }

                userAndBankStat[0] = stats1[3];//身份信息有盾
                userAndBankStat[1] = stats1[4];//银行卡信息
                adapter.notifyDataSetChanged();
                break;
            case CommonValue.REQUEST_CODE4:
                Log.e("927", "on提交资料Success: "+content);
                Log.e("927", "on提交资料Success: "+info.toString());
                openActivity(QuotaAuditActivity.class);
                finish();

                break;
            case CommonValue.REQUEST_CODE5:
//                Log.e(TAG, "芝麻芝麻onSuccess: "+content);
                String decrypt = DesUtils.decrypt(content, SPUtils.getDesKey(mContext));
                Log.e(TAG, "芝麻芝麻onSuccess: "+decrypt);
                Bundle bundle = new Bundle();
                bundle.putString("title", "芝麻信用");
                bundle.putString("url", decrypt);
                openActivity(WebViewActivity.class, bundle);

                break;

            case CommonValue.REQUEST_CODE6:
                showToast("身份验证成功");
//                list.get(list.size() - 2).setStat("已完善");
//                adapter.notifyDataSetChanged();
                updateUIMethod();
                //2017年9月27日12:48:19  修改

                break;
            case CommonValue.REQUEST_CODE7:
                //手机运营商认证成功，给后台发送数据成功，需要做的操作是刷新页面
                updateUIMethod();                //2017年9月27日12:48:19  修改

                break;
        }
    }

    /**
     * 刷新获取状态
     */
    private void updateUIMethod() {
        HttpUtils.getInstance().post(GetJsonUtils.getInstance().getRequest(HttpURL.AUTH_SUPPLEMENT, mContext,
                new String[]{"accessid"},
                new String[]{SPUtils.getAccessid(mContext)}),
                "", CommonValue.REQUEST_CODE3, this);
    }

    @Override
    public void onCacheSuccess(String content, Info info, int requestCode) {

    }

    @Override
    public void onError(Info info, int requestCode) {
        Log.e(TAG, "onError: "+info.toString());
        showToast(info.getMsg());
    }


    /**
     * 这个是身份证人脸识别回调
     * @param s
     */
    @Override
    public void onResult(String s) {
        if (!TextUtils.isEmpty(s)) {
            if (JsonUtils.getInstance().getJsonObject(s, "ret_code").equals("900001")) {
                showToast("用户取消验证");
                return;
            } else if (JsonUtils.getInstance().getJsonObject(s, "ret_code").equals("900011")) {
                showToast("获取相机权限失败");
                return;
            } else if (JsonUtils.getInstance().getJsonObject(s, "ret_code").equals("000000") && JsonUtils.getInstance().getJsonObject(s, "result_auth").equals("T")) {
                /**
                 *第三方授权同步返回信息提交，此处应该可以获取到身份证信息
                 */

                Log.e("onResult", "onResult: "+s);
                //身份证号
                idCardNO = JsonUtils.getInstance().getJsonObject(s, "id_no");
                //姓名
                realName = JsonUtils.getInstance().getJsonObject(s, "id_name");
                HttpUtils.getInstance().post(
                        GetJsonUtils.getInstance().getRequest(HttpURL.THIRD_RESPONSE, mContext,
                        new String[]
                                {
                                        "accessid"
                                , "response_type"
                                , "response_info"
                                },
                        new String[]
                                {
                                        SPUtils.getAccessid(mContext)
                                        , CommonValue.realname
                                        , s
                                })

                        ,
                        mContext
                        , ""
                        , CommonValue.REQUEST_CODE6
                        , this);
            } else {
                showToast("实名认证失败");
            }
        } else {
            showToast("系统忙,请重试");
        }

    }





}
